<script lang="ts" setup name="myMap">
import { shallowRef, onMounted, onUnmounted, provide, useAttrs } from 'vue';
import Map, { type MapOptions } from 'ol/Map';
import { mapContextKey } from './constants';
import View, { ViewOptions } from 'ol/View';
import 'ol/ol.css';
import { createLayers } from '@/map/utils/layers';

defineOptions({
  name: 'MyMap',
});

const props = defineProps<{
  mapOptions?: MapOptions;
  viewOptions?: ViewOptions;
}>();

const attrs = useAttrs();

defineEmits({
  beforeInit: (map: Map) => map,
});

let map: Map | undefined = new Map({
  controls: [],
  ...props.mapOptions,
  layers: [
    // createLayers({
    //   type: 1,
    //   options: {},
    // }),
  ],
  view: new View({
    center: [126.98, 47.4],
    projection: 'EPSG:4326',
    zoom: 10,
    minZoom: 1,
    maxZoom: 20,
    ...attrs,
    ...props.viewOptions,
  }),
});

provide(mapContextKey, map);

const mapRef = shallowRef<HTMLElement>();

/**
 * 地图挂载
 */
onMounted(() => {
  map?.setTarget(mapRef.value);
});

/**
 * 组件销毁、卸载地图
 */
onUnmounted(() => {
  map?.setTarget(undefined);
  map = undefined;
});

const render = () => map?.render();
const updateSize = () => map?.updateSize();

defineExpose({
  map,
  mapRef,
  render,
  updateSize,
});
</script>

<template>
  <div class="my-map-wrap">
    <div class="map" ref="mapRef"></div>
    <slot></slot>
  </div>
</template>

<style>
.my-map-wrap,
.map {
  height: 100%;
  position: relative;
}
</style>
